//
//  WCNetworkAccessManager.m
//  WC
//
//  Created by 杨鑫 on 15/4/28.
//  Copyright (c) 2015年 智康. All rights reserved.
//

#import "HELNetworkManager.h"

//
@import CoreTelephony;

@interface HELNetworkManager ()

@property (strong, nonatomic) AFHTTPSessionManager *httpRequestOperationManager;
@property (strong, nonatomic) NSString *payUrl;

//退出后清空
@property (strong, nonatomic) NSMutableDictionary *urlTime;

@end

@implementation HELNetworkManager

+ (instancetype)sharedMg
{
    static HELNetworkManager *sharedMg = nil;
    //block
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMg = [[HELNetworkManager alloc] initPrivate];
    });
    return sharedMg;
}

// No one should call init
- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Singleton"
                                   reason:@"Use +[WCNetworkAccessManager sharedMg]"
                                 userInfo:nil];
    return nil;
}

- (NSString *)getWexinAccessTokenApi{

     NSDictionary *configs =[NSDictionary dictionaryWithContentsOfFile:[self getConfigFilePath]];
    NSString *model= configs[@"MODEL"];
    NSDictionary *dict =configs[@"WexinAccessTotaken"];
    ;

    return  [NSString stringWithFormat:@"%@/care-wechat/wechat/getToken",dict[model]];
}

- (instancetype)initPrivate
{
    self = [super init];
    if (self) {
        NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:[self getConfigFilePath]];
        NSString *model =nil;
#if DEBUG
        model = configs[@"MODEL"];
        
        
        
#else
        model =@"appstoreUrl";
        
#endif
        NSDictionary *urls = configs[@"URLS"];
        NSDictionary *payUrls = configs[@"PAYS"];
        
        _bathURL = urls[model];
        
        _payUrl = payUrls[model];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 30;
        manager.securityPolicy.allowInvalidCertificates = [configs[@"HTTPS"] boolValue];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
         self.httpRequestOperationManager = manager;
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        _urlTime = [[NSMutableDictionary alloc] init];
        
        // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        // 检测网络连接的单例,网络变化时的回调方法
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if (status == AFNetworkReachabilityStatusUnknown) {
                self.netStatus = NetworkStatusUnknow;
            } else if (status == AFNetworkReachabilityStatusNotReachable) {
                self.netStatus = NetworkStatusNO;
            } else if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
                CTTelephonyNetworkInfo *networkStatus = [[CTTelephonyNetworkInfo alloc]init];
                NSString *currentStatus  = networkStatus.currentRadioAccessTechnology;
                if (currentStatus == CTRadioAccessTechnologyLTE){
                    self.netStatus = NetworkStatus4G;
                } else if (currentStatus == CTRadioAccessTechnologyeHRPD) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORevB) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORevA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORev0) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMA1x) {
                    self.netStatus = NetworkStatus2G;
                } else if (currentStatus == CTRadioAccessTechnologyHSUPA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyHSDPA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyWCDMA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyEdge) {
                    self.netStatus = NetworkStatus2G;
                } else if (currentStatus == CTRadioAccessTechnologyGPRS) {
                    self.netStatus = NetworkStatus2G;
                }
            } else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
                self.netStatus = NetworkStatusWIFI;
            } else {
                self.netStatus = NetworkStatusUnknow;
            }
        }];
    }
    return self;
}
- (void)setNetStatus:(HELNetworkStatus)netStatus{
    _netStatus = netStatus;
}
#pragma mark - record time

- (NSTimeInterval)timeSinceLastUrl:(NSString *)url
{
    NSDate *current = [NSDate date];
    NSDate *date = _urlTime[url];
    if (date) {
        return [current timeIntervalSinceDate:date];
    } else {
        return [current timeIntervalSince1970];
    }
}

- (void)recordTime:(NSString *)url
{
    [_urlTime setValue:[NSDate date] forKey:url];
}

- (void)resetTimeDic
{
    [_urlTime removeAllObjects];
}


- (NSString *)getBaseUrl{
    return _bathURL;
}

#pragma mark - http

- (NSURLSessionDataTask *)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)(id responseObject))success
                        failure:(void (^)(NSString *err))failure
{
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
    NSLog(@"%@",urlStr);
    NSURLSessionDataTask *sessionDataTask = [self.httpRequestOperationManager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        success(result);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([self showNetError:task with:error]);
    }];
    
    return sessionDataTask;
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)(id responseObject))success
                        failure:(void (^)(NSString *err))failure
{
   
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
       NSLog(@"%@",urlStr);
    NSURLSessionDataTask *task = [self.httpRequestOperationManager POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([self showNetError:task with:error]);

    }];
    
    return task;
}


#pragma mark-------------------上传图片-----------------

- (NSURLSessionDataTask *)UPLOAD:(NSString *)URLString
                      parameters:(id)parameters
                           image:(UIImage *)image
                        progress:(void (^)(CGFloat))progress
                         success:(void (^)(id))success
                         failure:(void (^)(NSString *))failure {
    
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
    
    NSURLSessionDataTask *task = [self.httpRequestOperationManager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传图片
        NSData *imageData = UIImagePNGRepresentation(image);
        if (!imageData) {
            imageData = UIImageJPEGRepresentation(image, 1);
        }
        CGFloat length = [imageData length]/1024.0/1024.0;
        while (length > 2) {
            imageData = UIImageJPEGRepresentation(image, 2.0/length);
            length = [imageData length]/1024.0/1024.0;
        }
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.png" mimeType:@"image/png"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        // 给Progress添加监听 KVO
        CGFloat percent = 1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        progress(percent);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        success(result);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([self showNetError:task with:error]);
    }];
    return task;
}


#pragma mark - Private

- (NSString *)showNetError:(NSURLSessionDataTask *)task with:(NSError *)error
{
    NSString *title;
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)task.response;
    NSInteger code = httpResponse.statusCode;
    if (code == 0) {
        NSInteger appleCode = error.code;
        if (appleCode == -1001) {
            title = @"连接超时";
        } else if (appleCode == -1004) {
            title = @"无法连接网络";
        }
    } else if (code == 400) {
        title = @"请求参数错误";
    } else if (code == 404) {
        title = @"找不到资源";
    } else if (code == 500) {
        title = @"服务器错误";
    }
    if (!title) {
        title = @"未知错误～";
    }
    return title;
}

#pragma mark - path

- (NSString *)getConfigFilePath
{
    return [[NSBundle mainBundle] pathForResource:@"urlConfig" ofType:@"plist"];
}




-(NSURLSessionDownloadTask *)downWithURLString:(NSString *)URLString progress:(void (^)(CGFloat))downProgress success:(void (^)(NSURL *))downSuccess failure:(void (^)(NSError *))downFailure{
    
    //    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
    
    //远程地址
    NSURL *URL = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //默认配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //AFN3.0+基于封住URLSession的句柄
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    
    manager.requestSerializer.HTTPShouldHandleCookies = YES;
    
    manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setTimeoutInterval:10];
    
    //把版本号信息传导请求头中
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"iOS-%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"MM-Version"];
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept" ];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/plain",nil];
    
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //下载Task操作
    NSURLSessionDownloadTask *task= [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        CGFloat progress = downloadProgress.completedUnitCount /downloadProgress.totalUnitCount;
        downProgress(progress);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        
        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];

        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            downFailure(error);
        }else{
            downSuccess(filePath);
        }
        
        
    }];
    
    
    
    return task;
    
    


}




@end
